import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const userInfo = ref(null)
  const token = ref('')
  const isLoggedIn = ref(false)
  const loginLoading = ref(false)
  
  // 计算属性
  const userName = computed(() => {
    return userInfo.value?.nickname || userInfo.value?.phone || '游客'
  })
  
  const userAvatar = computed(() => {
    return userInfo.value?.avatar || '/static/images/default-avatar.png'
  })
  
  const memberLevel = computed(() => {
    return userInfo.value?.memberLevel || 0
  })
  
  const memberLevelName = computed(() => {
    const levels = ['普通会员', '银卡会员', '金卡会员', 'VIP会员', '钻石会员']
    return levels[memberLevel.value] || '普通会员'
  })
  
  const memberLevelColor = computed(() => {
    const colors = ['#86868b', '#c0c0c0', '#ffd700', '#ff9500', '#af52de']
    return colors[memberLevel.value] || '#86868b'
  })
  
  const points = computed(() => {
    return userInfo.value?.points || 0
  })
  
  const balance = computed(() => {
    return userInfo.value?.balance || 0
  })
  
  const totalSpent = computed(() => {
    return userInfo.value?.totalSpent || 0
  })
  
  const memberProgress = computed(() => {
    // 计算会员等级进度
    const currentLevel = memberLevel.value
    const nextLevelPoints = [100, 500, 1000, 5000, 10000]

    if (currentLevel >= nextLevelPoints.length) return 100

    const currentPoints = points.value
    const targetPoints = nextLevelPoints[currentLevel]
    const prevPoints = currentLevel > 0 ? nextLevelPoints[currentLevel - 1] : 0

    return Math.min(100, ((currentPoints - prevPoints) / (targetPoints - prevPoints)) * 100)
  })

  // 用户详细信息的计算属性
  const userPhone = computed(() => {
    return userInfo.value?.phone || ''
  })

  const userGender = computed(() => {
    return userInfo.value?.gender || 0
  })

  const userBirthday = computed(() => {
    return userInfo.value?.birthday || ''
  })

  const userEmail = computed(() => {
    return userInfo.value?.email || ''
  })

  const userBio = computed(() => {
    return userInfo.value?.bio || ''
  })
  
  // 方法
  const login = async (loginData) => {
    loginLoading.value = true
    try {
      // 模拟登录API调用
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 模拟登录成功
      const mockUserInfo = {
        id: 1,
        phone: loginData.phone,
        nickname: '星际玩家',
        avatar: '/static/images/default-avatar.png',
        gender: 1,
        birthday: '1995-06-15',
        email: 'player@starnet.com',
        bio: '热爱游戏的网咖常客',
        memberLevel: 1,
        points: 280,
        balance: 50.00,
        totalSpent: 156.80,
        registerTime: new Date('2023-01-15'),
        lastLoginTime: new Date()
      }
      
      token.value = 'mock_token_' + Date.now()
      userInfo.value = mockUserInfo
      isLoggedIn.value = true
      
      // 保存到本地存储
      uni.setStorageSync('token', token.value)
      uni.setStorageSync('userInfo', userInfo.value)
      
      return { success: true }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: '登录失败，请重试' }
    } finally {
      loginLoading.value = false
    }
  }
  
  const logout = () => {
    userInfo.value = null
    token.value = ''
    isLoggedIn.value = false
    
    // 清除本地存储
    uni.removeStorageSync('token')
    uni.removeStorageSync('userInfo')
    
    // 显示退出成功提示
    uni.showToast({
      title: '已退出登录',
      icon: 'success'
    })
  }
  
  const checkLoginStatus = () => {
    const savedToken = uni.getStorageSync('token')
    const savedUserInfo = uni.getStorageSync('userInfo')
    
    if (savedToken && savedUserInfo) {
      token.value = savedToken
      userInfo.value = savedUserInfo
      isLoggedIn.value = true
      console.log('用户已登录:', savedUserInfo.nickname)
    }
  }
  
  const updateUserInfo = (newUserInfo) => {
    userInfo.value = { ...userInfo.value, ...newUserInfo }
    uni.setStorageSync('userInfo', userInfo.value)
  }

  const updateAvatar = (avatarUrl) => {
    if (userInfo.value) {
      userInfo.value.avatar = avatarUrl
      uni.setStorageSync('userInfo', userInfo.value)
      console.log('头像更新成功:', avatarUrl)
      return true
    }
    return false
  }

  const updateProfile = async (profileData) => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))

      if (userInfo.value) {
        // 更新用户信息
        userInfo.value = {
          ...userInfo.value,
          nickname: profileData.userName,
          gender: profileData.userGender,
          birthday: profileData.userBirthday,
          email: profileData.userEmail,
          bio: profileData.userBio
        }

        // 保存到本地存储
        uni.setStorageSync('userInfo', userInfo.value)

        console.log('个人资料更新成功:', userInfo.value)
        return { success: true }
      }

      return { success: false, message: '用户信息不存在' }
    } catch (error) {
      console.error('更新个人资料失败:', error)
      return { success: false, message: '更新失败，请重试' }
    }
  }
  
  const updateBalance = (amount) => {
    if (userInfo.value) {
      userInfo.value.balance = amount
      uni.setStorageSync('userInfo', userInfo.value)
    }
  }
  
  const updatePoints = (points) => {
    if (userInfo.value) {
      userInfo.value.points = points
      uni.setStorageSync('userInfo', userInfo.value)
    }
  }
  
  const addPoints = (points, reason = '消费奖励') => {
    if (userInfo.value) {
      userInfo.value.points += points
      uni.setStorageSync('userInfo', userInfo.value)
      
      // 显示积分奖励提示
      uni.showToast({
        title: `+${points}积分`,
        icon: 'success'
      })
    }
  }
  
  const addBalance = (amount, reason = '充值') => {
    if (userInfo.value && amount > 0) {
      userInfo.value.balance += amount
      userInfo.value.totalSpent += amount
      uni.setStorageSync('userInfo', userInfo.value)

      console.log(`余额增加: +${amount}, 原因: ${reason}, 当前余额: ${userInfo.value.balance}`)

      return true
    }
    return false
  }

  const consumeBalance = (amount) => {
    if (userInfo.value && userInfo.value.balance >= amount) {
      userInfo.value.balance -= amount
      userInfo.value.totalSpent += amount
      uni.setStorageSync('userInfo', userInfo.value)
      return true
    }
    return false
  }
  
  // 微信登录
  const wechatLogin = async () => {
    try {
      loginLoading.value = true
      
      // 模拟微信登录
      await new Promise(resolve => setTimeout(resolve, 800))
      
      const mockUserInfo = {
        id: 2,
        phone: '138****8888',
        nickname: '微信用户',
        avatar: '/static/images/wechat-avatar.png',
        memberLevel: 0,
        points: 0,
        balance: 0,
        totalSpent: 0,
        registerTime: new Date(),
        lastLoginTime: new Date(),
        loginType: 'wechat'
      }
      
      token.value = 'wechat_token_' + Date.now()
      userInfo.value = mockUserInfo
      isLoggedIn.value = true
      
      uni.setStorageSync('token', token.value)
      uni.setStorageSync('userInfo', userInfo.value)
      
      return { success: true }
    } catch (error) {
      console.error('微信登录失败:', error)
      return { success: false, message: '微信登录失败，请重试' }
    } finally {
      loginLoading.value = false
    }
  }
  
  // 手机号登录
  const phoneLogin = async (phone, code) => {
    return await login({
      phone,
      code,
      type: 'phone'
    })
  }
  
  // 发送验证码
  const sendSmsCode = async (phone) => {
    try {
      // 模拟发送验证码
      await new Promise(resolve => setTimeout(resolve, 500))
      
      // 模拟验证码：1234
      console.log('验证码已发送:', '1234')
      
      return { success: true }
    } catch (error) {
      console.error('发送验证码失败:', error)
      return { success: false, message: '发送验证码失败，请重试' }
    }
  }
  
  // 充值
  const recharge = async (amount, paymentMethod) => {
    try {
      // 模拟充值
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      if (userInfo.value) {
        userInfo.value.balance += amount
        uni.setStorageSync('userInfo', userInfo.value)
        
        uni.showToast({
          title: `充值成功 +¥${amount}`,
          icon: 'success'
        })
        
        return { success: true }
      }
      
      return { success: false, message: '充值失败' }
    } catch (error) {
      console.error('充值失败:', error)
      return { success: false, message: '充值失败，请重试' }
    }
  }
  
  return {
    // 状态
    userInfo,
    token,
    isLoggedIn,
    loginLoading,
    
    // 计算属性
    userName,
    userAvatar,
    userPhone,
    userGender,
    userBirthday,
    userEmail,
    userBio,
    memberLevel,
    memberLevelName,
    memberLevelColor,
    points,
    balance,
    totalSpent,
    memberProgress,
    
    // 方法
    login,
    logout,
    checkLoginStatus,
    updateUserInfo,
    updateAvatar,
    updateProfile,
    updateBalance,
    updatePoints,
    addBalance,
    addPoints,
    consumeBalance,
    wechatLogin,
    phoneLogin,
    sendSmsCode,
    recharge
  }
})
